<template>
  <view class="container">
    <!-- 倒计时卡片 -->
    <view class="countdown-card">
      <view class="card-header">
        <text class="current-time">{{ currentDateTime }}</text>
        <view class="settings-btn" @tap="openSettings">
          <image class="icon" src="../../assets/profile-active.png" mode="aspectFit" />
        </view>
      </view>
      
      <view class="countdown-content">
        <view class="countdown-header">
          <text class="title">距离下班</text>
          <text class="status">{{ isWorkday ? workStatus : '非工作日' }}</text>
        </view>

        <view class="countdown-timer">
          <view class="time-block">
            <text class="number">{{ workCountdown.hours }}</text>
            <text class="unit">小时</text>
          </view>
          <text class="separator">:</text>
          <view class="time-block">
            <text class="number">{{ workCountdown.minutes }}</text>
            <text class="unit">分钟</text>
          </view>
          <text class="separator">:</text>
          <view class="time-block">
            <text class="number">{{ workCountdown.seconds }}</text>
            <text class="unit">秒</text>
          </view>
        </view>

        <view class="work-progress">
          <text class="work-duration">今日已工作: {{ formatWorkDuration }}</text>
          <view class="progress-bar">
            <text class="time-label start">上班</text>
            <view class="progress" :style="{ width: workProgress + '%' }"></view>
            <text class="time-label end">下班</text>
          </view>
          <view class="time-info">
            <text>{{ currentPeriod }}</text>
            <text>剩余工作时间: {{ remainingWorkTime }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 今日收入卡片 -->
    <view class="today-income-card">
      <view class="income-header">
        <text class="title">今日已赚</text>
        <text class="subtitle">{{ isWorkday ? workStatus : '非工作日' }}</text>
      </view>
      <view class="income-amount">
        <text class="amount">¥{{ formatIncome }}</text>
        <view class="income-rate" v-if="isWorkday && isWorking">
          <text class="rate">+¥{{ hourlyRate }}/时</text>
          <view class="rate-tag">实时收入</view>
        </view>
      </view>
    </view>

    <!-- 收入统计卡片 -->
    <view class="income-stats-card">
      <view class="stats-grid">
        <view class="stats-item month">
          <text class="title">本月已赚</text>
          <text class="amount">¥{{ formatMonthIncome }}</text>
          <view class="estimate-tag">
            <text class="label">预计</text>
            <text class="value">¥{{ monthEstimate }}</text>
          </view>
        </view>
        <view class="stats-item year">
          <text class="title">今年已赚</text>
          <text class="amount">¥{{ formatYearIncome }}</text>
          <view class="estimate-tag">
            <text class="label">预计</text>
            <text class="value">¥{{ yearEstimate }}</text>
          </view>
        </view>
        <view class="stats-item total">
          <text class="title">入职已赚</text>
          <text class="amount">¥{{ formatTotalIncome }}</text>
          <text class="days">已入职 {{ workDays }} 天</text>
        </view>
      </view>
    </view>

    <!-- 发薪日倒计时卡片 -->
    <view class="payday-countdown-card">
      <view class="card-header">
        <text class="title">距离发薪日</text>
        <text class="next-payday">下次发薪: {{ nextPayday }}</text>
      </view>
      <view class="countdown-timer">
        <view class="time-block">
          <text class="number">{{ paydayCountdown.days }}</text>
          <text class="unit">天</text>
        </view>
        <text class="separator">:</text>
        <view class="time-block">
          <text class="number">{{ paydayCountdown.hours }}</text>
          <text class="unit">时</text>
        </view>
        <text class="separator">:</text>
        <view class="time-block">
          <text class="number">{{ paydayCountdown.minutes }}</text>
          <text class="unit">分</text>
        </view>
        <text class="separator">:</text>
        <view class="time-block">
          <text class="number">{{ paydayCountdown.seconds }}</text>
          <text class="unit">秒</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import Taro from '@tarojs/taro'
import { 
  formatDateTime, 
  calculateTimeLeft,
  formatTime,
  getWorkDaysInMonth,
  getWorkDaysInYear,
  getWorkDaysBetweenDates 
} from '../../utils/timeCalculator'
import eventBus from '../../utils/eventBus'

export default {
  name: 'Index',
  components: {
    // 如果使用了自定义组件，在这里声明
  },
  data() {
    return {
      timer: null,
      currentDateTime: '',
      workCountdown: {
        hours: '00',
        minutes: '00',
        seconds: '00'
      },
      workDuration: '0小时0分',
      workEndTime: '--:--',
      todayIncome: '0.00',
      monthIncome: '0.00',
      yearIncome: '0.00',
      totalIncome: '0.00',
      workDays: 0,
      hourlyRate: '0.00',
      currentTime: null,
      paydayCountdown: {
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00'
      }
    }
  },
  computed: {
    ...mapState({
      workSettings: state => state.workSettings
    }),
    isWorkday() {
      const now = new Date()
      const today = now.getDay() || 7
      return this.workSettings.workdays.includes(today)
    },
    workStatus() {
      if (!this.isWorking) {
        return this.workDuration
      }
      return '工作中'
    },
    isWorking() {
      if (!this.workSettings) return false
      
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)

      return (currentTime >= morningStart && currentTime <= morningEnd) ||
             (currentTime >= afternoonStart && currentTime <= afternoonEnd)
    },
    formatYearIncome() {
      if (!this.isWorkday || !this.isWorking) {
        return this.formatAmount(this.yearIncome)
      }
      
      if (!this.currentTime) {
        return this.formatAmount(this.yearIncome)
      }
      
      // 计算当天的工作收入
      const now = this.currentTime
      const dailyIncome = parseFloat(this.hourlyRate) * 8
      
      // 计算本年已完成工作日的收入
      const yearStart = new Date(now.getFullYear(), 0, 1)
      const completedWorkDays = getWorkDaysBetweenDates(
        yearStart,
        new Date(now.setHours(0, 0, 0, 0)),
        this.workSettings.workdays
      )
      let yearIncome = completedWorkDays * dailyIncome

      // 如果是工作日且在工作时间内，添加今日实时收入
      if (this.isWorkday && this.isWorking) {
        const startTime = new Date(now)
        const currentPeriod = this.getCurrentWorkPeriod()
        if (currentPeriod === 'morning') {
          const [hours, minutes] = this.workSettings.morningStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        } else {
          const [hours, minutes] = this.workSettings.afternoonStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        }
        const workMs = now.getTime() - startTime.getTime()
        const workHours = workMs / (1000 * 60 * 60)
        yearIncome += workHours * parseFloat(this.hourlyRate)
      }

      // 添加动态效果和格式化
      const parts = yearIncome.toFixed(2).split('.')
      const integer = parts[0]
      const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      const randomDecimal = Math.floor(Math.random() * 100)
      return formattedInteger + '.' + randomDecimal.toString().padStart(2, '0')
    },

    formatTotalIncome() {
      if (!this.isWorkday || !this.isWorking) {
        return this.formatAmount(this.totalIncome)
      }
      
      if (!this.currentTime) {
        return this.formatAmount(this.totalIncome)
      }
      
      // 计算当天的工作收入
      const now = this.currentTime
      const dailyIncome = parseFloat(this.hourlyRate) * 8
      
      // 计算入职以来已完成工作日的收入
      const joinDate = new Date(this.workSettings.joinDate)
      const completedWorkDays = getWorkDaysBetweenDates(
        joinDate,
        new Date(now.setHours(0, 0, 0, 0)),
        this.workSettings.workdays
      )
      let totalIncome = completedWorkDays * dailyIncome

      // 如果是工作日且在工作时间内，添加今日实时收入
      if (this.isWorkday && this.isWorking) {
        const startTime = new Date(now)
        const currentPeriod = this.getCurrentWorkPeriod()
        if (currentPeriod === 'morning') {
          const [hours, minutes] = this.workSettings.morningStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        } else {
          const [hours, minutes] = this.workSettings.afternoonStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        }
        const workMs = now - startTime
        const workHours = workMs / (1000 * 60 * 60)
        totalIncome += workHours * parseFloat(this.hourlyRate)
      }

      // 添加动态效果和格式化
      const parts = totalIncome.toFixed(2).split('.')
      const integer = parts[0]
      const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      const randomDecimal = Math.floor(Math.random() * 100)
      return formattedInteger + '.' + randomDecimal.toString().padStart(2, '0')
    },

    monthEstimate() {
      if (this.workSettings.salary.type === 'monthly') {
        return this.formatAmount(this.workSettings.salary.amount)
      }
      
      const now = new Date()
      const remainingWorkDays = getWorkDaysInMonth(
        now.getFullYear(),
        now.getMonth(),
        this.workSettings.workdays
      )
      const dailyIncome = parseFloat(this.hourlyRate) * 8
      const total = parseFloat(this.monthIncome) + (dailyIncome * remainingWorkDays)
      return this.formatAmount(total)
    },

    yearEstimate() {
      if (this.workSettings.salary.type === 'monthly') {
        return this.formatAmount(this.workSettings.salary.amount * 12)
      }
      
      const now = new Date()
      const remainingWorkDays = getWorkDaysInYear(
        now.getFullYear(),
        this.workSettings.workdays
      )
      const dailyIncome = parseFloat(this.hourlyRate) * 8
      const total = parseFloat(this.yearIncome) + (dailyIncome * remainingWorkDays)
      return this.formatAmount(total)
    },

    nextPayday() {
      const now = new Date()
      const currentDay = now.getDate()
      const payday = this.workSettings.payday || 15
      const paydayTime = this.workSettings.paydayTime || '12:00'
      const payParts = paydayTime.split(':')
      const payHour = payParts[0]
      const payMinute = payParts[1]
      let nextPaydayDate = new Date(now.getFullYear(), now.getMonth(), payday, parseInt(payHour), parseInt(payMinute), 0)
      
      // 如果当前日期已过发薪日，计算下个月的发薪日
      if (currentDay > payday) {
        nextPaydayDate = new Date(now.getFullYear(), now.getMonth() + 1, payday, parseInt(payHour), parseInt(payMinute), 0)
      }
      
      return nextPaydayDate.toLocaleDateString('zh-CN', {
        month: 'long',
        day: 'numeric'
      }) + ' ' + paydayTime
    },

    formatIncome() {
      if (!this.isWorkday || !this.isWorking) {
        return this.todayIncome
      }
      const now = this.currentTime || new Date()
      const startTime = new Date(now)
      
      // 根据当前时间判断是上午还是下午
      const currentPeriod = this.getCurrentWorkPeriod()
      if (currentPeriod === 'morning') {
        const [hours, minutes] = this.workSettings.morningStart.split(':')
        startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      } else {
        const [hours, minutes] = this.workSettings.afternoonStart.split(':')
        startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      }
      
      const workMs = now.getTime() - startTime.getTime()
      const workHours = workMs / (1000 * 60 * 60)
      const income = workHours * parseFloat(this.hourlyRate)

      return income.toFixed(2)
    },

    workProgress() {
      if (!this.isWorkday || !this.isWorking) return 0

      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()

      // 计算总工作时长（分钟）
      const morningDuration = this.getMinutesFromTime(this.workSettings.morningEnd) - 
                             this.getMinutesFromTime(this.workSettings.morningStart)
      const afternoonDuration = this.getMinutesFromTime(this.workSettings.afternoonEnd) - 
                               this.getMinutesFromTime(this.workSettings.afternoonStart)
      const totalWorkMinutes = morningDuration + afternoonDuration

      // 计算已工作时长
      let workedMinutes = 0
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)

      if (currentTime >= morningStart && currentTime <= morningEnd) {
        workedMinutes = currentTime - morningStart
      } else if (currentTime > morningEnd && currentTime < afternoonStart) {
        workedMinutes = morningDuration
      } else if (currentTime >= afternoonStart && currentTime <= afternoonEnd) {
        workedMinutes = morningDuration + (currentTime - afternoonStart)
      } else if (currentTime > afternoonEnd) {
        workedMinutes = totalWorkMinutes
      }

      return Math.min(100, Math.max(0, (workedMinutes / totalWorkMinutes) * 100))
    },

    formatWorkDuration() {
      if (!this.isWorkday) return '非工作日'
      if (!this.isWorking) return '未开始工作'
      
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)
      
      let workedMinutes = 0
      if (currentTime >= morningStart && currentTime <= morningEnd) {
        workedMinutes = currentTime - morningStart
      } else if (currentTime > morningEnd && currentTime < afternoonStart) {
        workedMinutes = morningEnd - morningStart
      } else if (currentTime >= afternoonStart && currentTime <= afternoonEnd) {
        workedMinutes = (morningEnd - morningStart) + (currentTime - afternoonStart)
      }
      
      const hours = Math.floor(workedMinutes / 60)
      const minutes = workedMinutes % 60
      return hours > 0 ? 
        `${hours}小时${minutes}分钟` : 
        `${minutes}分钟`
    },

    formatMonthIncome() {
      if (!this.isWorkday || !this.isWorking) {
        return this.formatAmount(this.monthIncome)
      }
      
      // 计算当天的工作收入
      const now = this.currentTime || new Date()
      const dailyIncome = parseFloat(this.hourlyRate) * 8
      
      // 计算本月已完成工作日的收入
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      // 创建一个新的日期对象，避免修改原始的 now
      const todayStart = new Date(now)
      todayStart.setHours(0, 0, 0, 0)
      const completedWorkDays = getWorkDaysBetweenDates(
        monthStart,
        todayStart,
        this.workSettings.workdays
      )
      let monthIncome = completedWorkDays * dailyIncome

      // 如果是工作日且在工作时间内，添加今日实时收入
      if (this.isWorkday && this.isWorking) {
        const startTime = new Date(now)
        const currentPeriod = this.getCurrentWorkPeriod()
        if (currentPeriod === 'morning') {
          const [hours, minutes] = this.workSettings.morningStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        } else {
          const [hours, minutes] = this.workSettings.afternoonStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        }
        const workMs = now - startTime
        const workHours = workMs / (1000 * 60 * 60)
        monthIncome += workHours * parseFloat(this.hourlyRate)
      }

      // 添加动态效果
      const parts = monthIncome.toFixed(2).split('.')
      const integer = parts[0]
      const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      const randomDecimal = Math.floor(Math.random() * 100)
      return formattedInteger + '.' + randomDecimal.toString().padStart(2, '0')
    },

    currentPeriod() {
      if (!this.isWorkday || !this.isWorking) return ''
      
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      
      return currentTime >= morningStart && currentTime <= morningEnd ? '上午工作时段' : '下午工作时段'
    },

    remainingWorkTime() {
      if (!this.isWorkday) return '非工作日'
      if (!this.isWorking) return '非工作时间'

      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)
      
      // 计算总工作时长
      const totalWorkMinutes = this.getWorkHours() * 60
      
      // 计算已工作时长
      let workedMinutes = 0
      if (currentTime >= morningStart && currentTime <= morningEnd) {
        workedMinutes = currentTime - morningStart
      } else if (currentTime > morningEnd && currentTime < afternoonStart) {
        workedMinutes = morningEnd - morningStart
      } else if (currentTime >= afternoonStart && currentTime <= afternoonEnd) {
        workedMinutes = (morningEnd - morningStart) + (currentTime - afternoonStart)
      }

      const remainingMinutes = totalWorkMinutes - workedMinutes

      if (remainingMinutes > 0) {
        const hours = Math.floor(remainingMinutes / 60)
        const minutes = remainingMinutes % 60
        return hours > 0 ? 
          `${hours}小时${minutes}分钟` : 
          `${minutes}分钟`
      }
      return '非工作时间'
    }
  },

  onShow() {
    // 重新加载设置并更新数据
    this.$store.dispatch('loadSettings').then(() => {
      this.calculateHourlyRate()
      this.updateMonthAndYearIncome()
      this.calculateWorkDays()
      // 如果是工作日且在工作时间，更新实时收入
      if (this.isWorkday && this.isWorking) {
        this.calculateIncome(new Date())
        this.updateIncomeStats(true)
      }
    })
  },

  created() {
    this.currentTime = new Date()
  },

  mounted() {
    this.$store.dispatch('loadSettings').then(() => {
      this.startTimer()
      this.calculateHourlyRate()
      this.updateMonthAndYearIncome()
      this.calculateWorkDays()
    })
    
    // 监听设置更新事件
    eventBus.$on('settings-updated', this.handleSettingsUpdate)
  },

  beforeDestroy() {
    this.clearTimer()
    // 移除事件监听
    eventBus.$off('settings-updated', this.handleSettingsUpdate)
  },

  methods: {
    startTimer() {
      this.updateTime()
      this.timer = setInterval(this.updateTime, 1000)
    },

    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },

    updateTime() {
      const now = new Date()
      this.currentTime = now
      this.currentDateTime = formatDateTime(now)
      
      // 更新所有收入统计
      if (this.isWorkday && this.isWorking) {
        this.calculateIncome(now)
        this.updateIncomeStats(true)
      }
      
      // 检查是否是工作日
      if (!this.isWorkday) {
        this.workCountdown = { hours: '00', minutes: '00', seconds: '00' }
        this.workDuration = '非工作日'
        this.workEndTime = '--:--'
        // 非工作日时重置收入
        this.todayIncome = '0.00'
        this.updateIncomeStats(false)
        return
      }
      
      // 更新下班倒计时
      const endTime = new Date(now)
      const [hours, minutes] = this.workSettings.afternoonEnd.split(':')
      endTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      
      // 获取上班时间
      const startTime = new Date(now)
      const [startHours, startMinutes] = this.workSettings.morningStart.split(':')
      startTime.setHours(parseInt(startHours), parseInt(startMinutes), 0, 0)
      
      // 如果还没到上班时间
      if (now < startTime) {
        this.workCountdown = { hours: '00', minutes: '00', seconds: '00' }
        this.workDuration = '未开始'
        this.workEndTime = this.workSettings.endTime
        return
      }
      
      // 如果已经下班
      if (now > endTime) {
        this.workCountdown = { hours: '00', minutes: '00', seconds: '00' }
        this.workDuration = '已下班'
        this.workEndTime = '--:--'
      } else {
        const diffMs = endTime - now
        const hours = Math.floor(diffMs / (1000 * 60 * 60))
        const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
        const seconds = Math.floor((diffMs % (1000 * 60)) / 1000)
        
        this.workCountdown = {
          hours: hours.toString().padStart(2, '0'),
          minutes: minutes.toString().padStart(2, '0'),
          seconds: seconds.toString().padStart(2, '0')
        }
        
        // 更新工作时长
        const workMs = now - startTime
        const workHours = Math.floor(workMs / (1000 * 60 * 60))
        const workMinutes = Math.floor((workMs % (1000 * 60 * 60)) / (1000 * 60))
        this.workDuration = `${workHours}小时${workMinutes}分`
        this.workEndTime = this.workSettings.endTime
      }
      
      // 定期更新收入统计
      this.updateIncomeStats(true)
      
      // 更新发薪日倒计时
      this.updatePaydayCountdown()
    },

    calculateIncome(now) {
      if (!this.isWorkday || !this.isWorking) {
        this.todayIncome = '0.00'
        return
      }
      
      const startTime = new Date(now)
      const currentPeriod = this.getCurrentWorkPeriod()
      if (currentPeriod === 'morning') {
        const [hours, minutes] = this.workSettings.morningStart.split(':')
        startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      } else {
        const [hours, minutes] = this.workSettings.afternoonStart.split(':')
        startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
      }
      
      const workMs = now.getTime() - startTime.getTime()
      const workHours = workMs / (1000 * 60 * 60)
      
      this.todayIncome = (workHours * parseFloat(this.hourlyRate)).toFixed(2)
    },

    openSettings() {
      Taro.navigateTo({
        url: '/pages/settings/index'
      })
    },

    calculateHourlyRate() {
      if (!this.workSettings || !this.workSettings.salary) return
      
      if (this.workSettings.salary.type === 'monthly') {
        // 获取当月工作日数
        const now = new Date()
        const monthWorkDays = getWorkDaysInMonth(
          now.getFullYear(),
          now.getMonth(),
          this.workSettings.workdays
        )
        // 月薪除以工作日再除以每日工作时长
        const workHours = this.getWorkHours()
        if (monthWorkDays > 0 && workHours > 0) {
          this.hourlyRate = (this.workSettings.salary.amount / monthWorkDays / workHours).toFixed(2)
        } else {
          this.hourlyRate = '0.00'
        }
      } else {
        this.hourlyRate = this.workSettings.salary.amount.toFixed(2)
      }
    },

    updateMonthAndYearIncome() {
      if (!this.workSettings || !this.workSettings.salary) return
      
      const now = new Date()
      const workHours = this.getWorkHours()
      
      if (this.workSettings.salary.type === 'monthly') {
        // 月薪模式下，月收入就是固定的月薪
        this.monthIncome = this.workSettings.salary.amount.toFixed(2)
        // 年收入是月薪 * 12
        this.yearIncome = (this.workSettings.salary.amount * 12).toFixed(2)
      } else {
        // 时薪模式下，需要计算工作日数
        const monthWorkDays = getWorkDaysInMonth(
          now.getFullYear(),
          now.getMonth(),
          this.workSettings.workdays
        )
        const yearWorkDays = getWorkDaysInYear(
          now.getFullYear(),
          this.workSettings.workdays
        )
        const dailyIncome = parseFloat(this.hourlyRate) * workHours
        
        this.monthIncome = (dailyIncome * monthWorkDays).toFixed(2)
        this.yearIncome = (dailyIncome * yearWorkDays).toFixed(2)
      }
    },

    calculateWorkDays() {
      const now = new Date()
      const joinDate = new Date(this.workSettings.joinDate)
      if (joinDate > now) {
        joinDate.setTime(now.getTime())
      }
      this.workDays = getWorkDaysBetweenDates(
        joinDate,
        now,
        this.workSettings.workdays
      )
      
      const dailyIncome = parseFloat(this.hourlyRate) * this.getWorkHours()
      this.totalIncome = (this.workDays * dailyIncome).toFixed(2)
    },

    updateIncomeStats(includeToday = true) {
      const now = new Date()
      const dailyIncome = parseFloat(this.hourlyRate) * this.getWorkHours()
      
      // 更新总收入
      const joinDate = new Date(this.workSettings.joinDate)
      if (joinDate > now) {
        joinDate.setTime(now.getTime())
      }
      const totalWorkDays = getWorkDaysBetweenDates(
        joinDate,
        new Date(now.setHours(0, 0, 0, 0)),
        this.workSettings.workdays
      )
      let totalIncome = dailyIncome * totalWorkDays
      
      // 如果是工作日且需要包含今天的收入
      if (includeToday && this.isWorkday && this.isWorking) {
        const startTime = new Date(now)
        const currentPeriod = this.getCurrentWorkPeriod()
        if (currentPeriod === 'morning') {
          const [hours, minutes] = this.workSettings.morningStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        } else {
          const [hours, minutes] = this.workSettings.afternoonStart.split(':')
          startTime.setHours(parseInt(hours), parseInt(minutes), 0, 0)
        }
        const workMs = now.getTime() - startTime.getTime()
        const workHours = workMs / (1000 * 60 * 60)
        totalIncome += workHours * parseFloat(this.hourlyRate)
      }
      this.totalIncome = totalIncome.toFixed(2)
    },

    updatePaydayCountdown() {
      const now = new Date()
      const currentDay = now.getDate()
      const payday = this.workSettings.payday || 15
      const paydayTime = this.workSettings.paydayTime || '12:00'
      const payParts = paydayTime.split(':')
      const payHour = payParts[0]
      const payMinute = payParts[1]
      let nextPaydayDate = new Date(now.getFullYear(), now.getMonth(), payday, parseInt(payHour), parseInt(payMinute), 0)
      
      // 如果当前日期已过发薪日，计算下个月的发薪日
      if (currentDay > payday) {
        nextPaydayDate = new Date(now.getFullYear(), now.getMonth() + 1, payday, parseInt(payHour), parseInt(payMinute), 0)
      }
      
      const diffMs = nextPaydayDate - now
      const days = Math.floor(diffMs / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diffMs % (1000 * 60)) / 1000)
      
      this.paydayCountdown = {
        days: days.toString().padStart(2, '0'),
        hours: hours.toString().padStart(2, '0'),
        minutes: minutes.toString().padStart(2, '0'),
        seconds: seconds.toString().padStart(2, '0')
      }
    },

    handleSettingsUpdate() {
      // 重新计算所有数据
      this.calculateHourlyRate()
      this.updateMonthAndYearIncome()
      this.calculateWorkDays()
      // 如果是工作日且在工作时间，更新实时收入
      if (this.isWorkday && this.isWorking) {
        this.calculateIncome(new Date())
        this.updateIncomeStats(true)
      }
    },

    formatAmount(amount) {
      const num = parseFloat(amount)
      if (isNaN(num)) return '0.00'
      if (num >= 10000) {
        const wan = (num / 10000).toFixed(2)
        return wan + '万'
      }
      return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    getMinutesFromTime(timeString) {
      if (!timeString) return 0
      const [hours, minutes] = timeString.split(':').map(Number)
      return hours * 60 + minutes
    },

    getWorkHours() {
      if (!this.workSettings) return 0
      
      // 计算每日工作时长
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      const afternoonStart = this.getMinutesFromTime(this.workSettings.afternoonStart)
      const afternoonEnd = this.getMinutesFromTime(this.workSettings.afternoonEnd)
      
      const morningHours = (morningEnd - morningStart) / 60
      const afternoonHours = (afternoonEnd - afternoonStart) / 60
      
      return morningHours + afternoonHours
    },

    getCurrentWorkPeriod() {
      if (!this.workSettings) return 'morning'
      
      const now = new Date()
      const currentTime = now.getHours() * 60 + now.getMinutes()
      const morningStart = this.getMinutesFromTime(this.workSettings.morningStart)
      const morningEnd = this.getMinutesFromTime(this.workSettings.morningEnd)
      
      return currentTime >= morningStart && currentTime <= morningEnd ? 'morning' : 'afternoon'
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f8fafc;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.countdown-card {
  background: #fff;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .current-time {
      font-size: 20px;
      color: #64748b;
    }

    .settings-btn {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f1f5f9;
      border-radius: 50%;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
        opacity: 0.8;
      }
      
      .icon {
        width: 20px;
        height: 20px;
      }
    }
  }
  
  .countdown-content {
    .countdown-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 32px;

      .title {
        font-size: 24px;
        color: #1e293b;
        font-weight: 600;
      }

      .status {
        font-size: 18px;
        color: #64748b;
        background: #f1f5f9;
        padding: 6px 12px;
        border-radius: 20px;
      }
    }
    
    .countdown-timer {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 16px;
      margin-bottom: 0;

      .time-block {
        background: #f8fafc;
        border-radius: 16px;
        padding: 16px;
        min-width: 100px;
        text-align: center;

        .number {
          font-size: 48px;
          font-weight: 700;
          color: #1e293b;
          display: block;
          margin-bottom: 4px;
          font-family: monospace;
        }

        .unit {
          font-size: 18px;
          color: #64748b;
        }
      }

      .separator {
        font-size: 36px;
        font-weight: 300;
        color: #94a3b8;
        margin-top: -8px;
      }
    }

    .work-progress {
      margin-top: 24px;
      
      .work-duration {
        font-size: 18px;
        color: #64748b;
        margin-bottom: 16px;
        display: block;
      }
      
      .progress-bar {
        position: relative;
        height: 8px;
        background: #f1f5f9;
        border-radius: 4px;
        margin: 24px 0;
        
        .progress {
          height: 100%;
          background: #3b82f6;
          border-radius: 4px;
          transition: width 0.3s ease;
        }
        
        .time-label {
          position: absolute;
          top: -24px;
          font-size: 16px;
          color: #64748b;
          
          &.start {
            left: 0;
          }
          
          &.end {
            right: 0;
          }
        }
      }
      
      .time-info {
        display: flex;
        justify-content: space-between;
        font-size: 16px;
        color: #64748b;
      }
    }
  }
}

.income-stats-card {
  background: #fff;
  border-radius: 20px;
  padding: 24px;
  
  .stats-grid {
    display: flex;
    gap: 16px;
    
    .stats-item {
      flex: 1;
      padding: 16px;
      background: #f8fafc;
      border-radius: 16px;
      
      .title {
        font-size: 18px;
        color: #64748b;
        margin-bottom: 8px;
      }
      
      .amount {
        font-size: 36px;
        color: #1e293b;
        font-weight: 600;
        display: block;
        margin-bottom: 8px;
        font-family: monospace;
      }
      
      .estimate-tag {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        background: rgba(59, 130, 246, 0.1);
        padding: 4px 8px;
        border-radius: 8px;
        
        .label {
          font-size: 16px;
          color: #3b82f6;
        }
        
        .value {
          font-size: 16px;
          color: #2563eb;
          font-weight: 600;
        }
      }
      
      .days {
        font-size: 12px;
        color: #94a3b8;
        display: block;
        margin-top: 4px;
      }
    }
  }
}

.payday-countdown-card {
  background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(139, 92, 246, 0.2);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .title {
      font-size: 24px;
      color: rgba(255, 255, 255, 0.9);
      font-weight: 500;
    }

    .next-payday {
      font-size: 18px;
      color: rgba(255, 255, 255, 0.7);
      background: rgba(255, 255, 255, 0.1);
      padding: 4px 12px;
      border-radius: 12px;
    }
  }

  .countdown-timer {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 16px;

    .time-block {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 16px;
      min-width: 80px;
      text-align: center;

      .number {
        font-size: 48px;
        font-weight: 700;
        color: #fff;
        display: block;
        margin-bottom: 4px;
        font-family: monospace;
      }

      .unit {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.7);
      }
    }

    .separator {
      font-size: 32px;
      font-weight: 300;
      color: rgba(255, 255, 255, 0.5);
      margin-top: -8px;
    }
  }
}

.today-income-card {
  background: #fff;
  border-radius: 24px;
  padding: 24px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.05);
  
  .income-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .title {
      font-size: 24px;
      color: #1e293b;
      font-weight: 600;
    }
    
    .subtitle {
      font-size: 18px;
      color: #64748b;
      background: #f1f5f9;
      padding: 4px 12px;
      border-radius: 12px;
    }
  }
  
  .income-amount {
    margin-bottom: 24px;
    
    .amount {
      font-size: 48px;
      color: #1e293b;
      font-weight: 700;
      font-family: monospace;
    }
    
    .income-rate {
      margin-top: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .rate {
        font-size: 18px;
        color: #64748b;
      }
      
      .rate-tag {
        font-size: 16px;
        color: #3b82f6;
        background: rgba(59, 130, 246, 0.1);
        padding: 2px 8px;
        border-radius: 8px;
      }
    }
  }
}
</style>
